<template>
  <div class="articles">
    <div class="site-content animate">
      <main class="site-main">
        <article class="hentry">
          <!-- 文章头部 -->
          <header class="entry-header">
            <!-- 标题输出 -->
            <el-input
              class="entry-title"
              v-model="articleForm.title"
              placeholder="请输入标题"
            ></el-input>
          </header>

          <el-select
            v-model="articleForm.category"
            multiple
            filterable
            default-first-option
            placeholder="请选择文章标签"
            style="width:100%"
          >
            <el-option
              v-for="item in categorys"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>

          <mavon-editor
            v-model="articleForm.content"
            ref=md
            @imgAdd="handleEditorImgAdd"
            @save="save"
            style="margin:20px 0"
          />
          <el-upload
            class="avatar-uploader"
            :http-request="uploadBanner"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <div
              slot="tip"
              class="el-upload__tip"
            >上传封面、只能上传jpg/png文件，且不超过500kb</div>
            <img
              v-if="articleForm.banner"
              :src="articleForm.banner"
              class="avatar"
            >
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            ></i>
          </el-upload>
          <hr style="margin:15px 0;">
          <header class="entry-header">
            <el-button
              type="primary"
              v-show="articleForm.status==1"
              v-on:click="save()"
              size="medium"
            >保存草稿</el-button>
            <el-button
              type="success"
              v-on:click="submit()"
              style="marrginLeft:10px"
              size="medium"
            >发布</el-button>
          </header>

        </article>

      </main>

    </div>
  </div>
</template>

<script>
import sectionTitle from "@/components/section-title";
import {
  edit,
  savePost,
  uploadFile,
  notLogin,
  fetchCategoryName,
} from "../api";
export default {
  name: "articles",
  data() {
    return {
      postId: null,
      articleForm: {
        id: "",
        title: "",
        content: "",
        banner: "",
        status: 1,
      },
      categorys: [],
      inputVisible: false,
      inputValue: "",
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
    };
  },
  components: {
    sectionTitle,
  },
  created() {
    this.postId = this.$route.params.id; // 123
    this.getArticle();
  },
  watch: {
    "$route.path": function (newVal, oldVal) {
      this.getArticle();
    },
  },
  mounted() {
    this.doDetchCategory();
  },

  methods: {
    isLogin() {
      notLogin();
    },
    getArticle() {
      //id=0代表是新写的博客。
      if (this.postId != "" && this.postId != 0) {
        edit({
          id: this.postId,
        })
          .then((res) => {
            this.articleForm = res.data;
            this.categorys = res.data.category
              .substring(1, res.data.category.length - 1)
              .replace(/\"/g, "")
              .split(",");
            console.log(this.categorys);

            this.articleForm.content = res.data.content;
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.doDetchCategory();
      }
    },
    save() {
      this.articleForm.status = 1;
      console.log(this.articleForm);
      savePost(this.articleForm).then((res) => {
        this.$notify({
          title: "成功",
          message: res.msg,
          type: "success",
        });
        this.$router.push("/");
      });
    },
    submit() {
      this.articleForm.status = 2;
      console.log(this.articleForm);
      savePost(this.articleForm).then((res) => {
        this.$notify({
          title: "成功",
          message: res.msg,
          type: "success",
        });
        this.$router.push("/");
      });
    },
    // 绑定@imgAdd event
    handleEditorImgAdd(pos, $file) {
      console.log(pos);
      let formdata = new FormData();
      formdata.append("file", $file);
      uploadFile(formdata).then((res) => {
        this.$notify({
          title: "成功",
          message: "上传成功",
          type: "success",
        });
        let url = res.data;
        let name = $file.name;
        if (name.includes("-")) {
          name = name.replace(/-/g, "");
        }
        let content = this.articleForm.content;
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)  这里是必须要有的
        if (content.includes(name)) {
          let oStr = `(${pos})`;
          let nStr = `(${url})`;
          let index = content.indexOf(oStr);
          let str = content.replace(oStr, "");
          let insertStr = (soure, start, newStr) => {
            return soure.slice(0, start) + newStr + soure.slice(start);
          };
          this.articleForm.content = insertStr(str, index, nStr);
        }
      });
    },
    handleAvatarSuccess(res, file) {
      console.log(res);
      this.articleForm.banner = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
    },
    uploadBanner: function (param) {
      //file就是当前添加的文件
      var fileObj = param.file;
      // FormData 对象
      var form = new FormData();
      // 文件对象,key是后台接受的参数名称
      form.append("file", fileObj);
      uploadFile(form).then((res) => {
        this.$notify({
          title: "成功",
          message: "上传成功",
          type: "success",
        });
        this.articleForm.banner = res.data;
        console.log(res);
      });
    },

    doDetchCategory() {
      fetchCategoryName().then((res) => {
        this.categorys = res.data;
      });
    },

    handleClose(tag) {
      this.categorys.splice(this.categorys.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.categorys.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
  },
};
</script>

<style lang="less" scoped>
.site-content {
  .site-main {
    padding: 80px 0 0 0;
  }
}

article.hentry {
  .entry-header {
    .entry-title {
      font-size: 23px;
      font-weight: 600;
      color: #737373;
      margin: 0.67em 0;

      &:before {
        margin-right: 6px;
        color: #d82e16;
        font-size: 20px;
        font-weight: 600;
      }
    }

    hr {
      height: 1px;
      border: 0;
      background: #efefef;
      margin: 15px 0;
    }

    .breadcrumbs {
      font-size: 14px;
      color: #d2d2d2;
      text-decoration: none;
      margin-bottom: 30px;
    }
  }

  footer.post-footer {
    width: 100%;
    padding: 20px 10px;
    margin-top: 30px;
    height: 65px;
    position: relative;

    i {
      font-size: 18px;
      margin-right: 5px;
    }

    .post-like {
      float: right;
      margin: 7px 0 0 20px;
    }

    .post-share {
      float: right;
      list-style: none;
      margin-right: 20px;
    }

    .donate {
      float: left;
      line-height: 36px;
      border-radius: 100%;
      -webkit-border-radius: 100%;
      -moz-border-radius: 100%;
      border: 1px solid #2b2b2b;

      &:hover {
        border: 1px solid goldenrod;

        span {
          color: goldenrod;
        }
      }

      span {
        color: #2b2b2b;
        padding: 10px;
        position: relative;
        cursor: pointer;
      }

      .donate_inner {
        display: none;
        margin: 0;
        list-style: none;
        position: absolute;
        left: 80px;
        top: -40px;
        background: #fff;
        padding: 10px;
        border: 1px solid #ddd;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
        border-radius: 3px;

        &.show {
          display: block;
        }

        li {
          float: left;
        }

        img {
          width: 100px;
        }

        p {
          text-align: center;
          font-size: 15px;
          color: #d2d2d2;
          line-height: 1rem;
        }
      }

      .donate_inner:after,
      .donate_inner:before {
        content: "";
        position: absolute;
        left: 0;
        bottom: 45%;
        margin-left: -8px;
        border-top: 8px solid transparent;
        border-bottom: 8px solid transparent;
        border-right: 8px solid #fff;
      }

      .donate_inner:before {
        left: -1px;
        border-right: 8px solid #ddd;
      }
    }

    .post-tags {
      margin: 7px 0 0 20px;
      float: left;
      text-transform: uppercase;

      a:hover {
        color: #ff6d6d;
      }
    }
  }

  .open-message {
    margin: 50px 0;
    position: relative;
    background: #2b2b2b;
    padding: 10px 30px;
    border-radius: 3px;
    font-size: 14px;
    color: #fff;

    &:after {
      content: "";
      border-left: 10px solid transparent;
      border-right: 10px solid transparent;
      border-bottom: 10px solid #2b2b2b;
      position: absolute;
      top: -8px;
      left: 48%;
    }

    p {
      margin: 10px 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    a {
      color: #a0dad0;
      padding: 0 5px;
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
